﻿using System.IO;
using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using PMP.Core.SignalR;
using PMP.Web.Core.Models;

namespace PMP.Web.Core;

public class Startup : AppStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddConsoleFormatter();
        services.AddJwt<JwtHandler>(enableGlobalAuthorize:true);
        services.AddSignalR(options =>
        {
            options.AddFilter(new ClientsNullCheckFilter());
        });
        services.AddSingleton<IUserIdProvider, HubUserIdProvider>();

        services.AddCorsAccessor();
        services.RegisterServices();

        services.AddControllers()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            }) // json
            .AddInjectWithUnifyResult<MyRESTfulResultProvider>() // Api统一返回格式
            ;

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();
        
        // 【关键配置】启用静态文件服务，指定Files文件夹为资源目录
        app.UseStaticFiles(new StaticFileOptions
        {
            // 物理路径：指向项目根目录下的Files文件夹
            FileProvider = new PhysicalFileProvider(
                Path.Combine(env.ContentRootPath, "Files")
            ),
            // 访问路径：通过URL中的"/Files"映射到物理文件夹（与文件夹名保持一致，方便记忆）
            RequestPath = "/Files"
        });
        
        app.UseCorsAccessor();

        app.UseAuthentication();
        app.UseAuthorization();
        
        app.MyConfigure();

        app.Use((context, next) =>
        {
            context.Request.EnableBuffering();
            return next();
        });
        app.UseEndpoints(endpoints =>
        {
            // SignalR 集线器
            endpoints.MapHubs();
            endpoints.MapControllers();
        });
    }
}
